rm(list=ls())
library(statnet)
data<-read.csv("NCnorm.csv")
setwd("C:\\Documents and Settings\\Laura Metzger\\Desktop\\Dissertation\\Chapter2\\Data\\")
load("NCnet072.RData")



AM2<-AM
for(i in 1:nrow(AM)){
AM2[,i]<-AM[,i]/Spons[i]
}

AM2<-ifelse(is.na(AM2)==TRUE, 0, AM2)

AMst<-ifelse(AM2>=mean(AM2)+mean(sd(AM2)),1,0)
AMwk<-ifelse(AM2>0 & AM2<mean(AM2)+mean(sd(AM2)), 1, 0)

memb<-vector(mode="numeric", length=nrow(AM))
for(i in 1:length(memb)){
for(j in 1:nrow(data)){
z<-match(row.names(AM)[i], data$billauthor[j])
if(is.na(z)==FALSE){
memb[i]<-data$party[j]
}
}
}

memb[17]<-1
memb[30]<-1
memb[52]<-1
memb[65]<-1
memb[70]<-1
memb[3]<-1
memb[10]<-0
memb[71]<-0



AMnet<-network(AM)
r<-as.vector(AM)
r<-r[r!=0]
set.edge.attribute(AMnet, "values", r, e=1:length(r))
get.edge.attribute(AMnet$mel, "values")
AMnet<-network.adjacency(AM, AMnet, ignore.eval=FALSE, names.eval="values")

same.party<-matrix(0, 126, 126)
for(i in 1:126){
for(j in 1:126){
same.party[i,j]<-ifelse(memb[i]==memb[j], 1, 0)
}
}




mod<-ergmm(AMnet~latentcov(same.party)+latent(d=2), family="Poisson", response="values", verbose=1)
dput(mod, file="results.txt")

r<-predict.ergmm(mod)
f<-AM-r

pdf("DensityDifference97.pdf")
plot(density(f), main="Density of Differences between Observed and Predicted Connections", xlab="Difference in Connections")
dev.off()

pdf("DensityObsPre97.pdf")
plot(density(AM), col="red", xlim=c(-5, 20), main="Density of Observed and Predicted Connections in the NC House")
lines(density(r), col="blue", xlim=c(-5, 20))
legend(10, 0.25, c("Observed","Predicted"), col=c("red", "blue"), lty=c(1,1))
dev.off()

pdf("positions97.pdf")
plot(mod, vertex.col=memb+1, main="MKL Latent Positions of NC House in 2007", label=TRUE, edge.col=0, what="mkl")
abline(0,0)
abline(v=0)
legend(-5, 6, c("Democrats","Republicans"), col=c("red","black"), lty=c(1,1), lwd=c(2,2))
dev.off()